﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Resources;
using System.Windows.Controls;
using System.Windows.Markup;

namespace Foundation.MarkupExtensions
{
    /// <summary>
    /// XAML extension for picturies.
    /// </summary>
    public class Picture : MarkupExtension
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Picture"/> class.
        /// </summary>
        /// <param name="key">The path.</param>
        public Picture(string key)
        {
            Key = key.EndsWith(".png") ? key : key + ".png";
            Width = Height = 16;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Picture"/> class.
        /// </summary>
        /// <param name="key">The path.</param>
        /// <param name="size">The size.</param>
        public Picture(string key, int size)
        {
            Key = key.EndsWith(".png") ? key : key + ".png";
            Width = Height = size;
        }

        /// <summary>
        /// Gets the resource managers.
        /// </summary>
        public static readonly List<ResourceManager> Managers = new List<ResourceManager>();

        /// <summary>
        /// Gets or sets the path.
        /// </summary>
        /// <value>
        /// The path.
        /// </value>
        public string Key { get; set; }

        /// <summary>
        /// Gets or sets the width.
        /// </summary>
        /// <value>
        /// The width.
        /// </value>
        [DefaultValue(double.NaN)]
        public double Width { get; set; }

        /// <summary>
        /// Gets or sets the height.
        /// </summary>
        /// <value>
        /// The height.
        /// </value>
        [DefaultValue(double.NaN)]
        public double Height { get; set; }

        /// <summary>
        /// When implemented in a derived class, returns an object that is set as the value of the target property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        /// The object value to set on the property where the extension is applied.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var value = Managers.Select(m => m.GetObject(Key)).LastOrDefault(v => v != null) as Image;
            if (value == null) return null;
            if (double.IsNaN(Height)) Height = value.Height;
            else value.Height = Height;
            if (double.IsNaN(Width)) Width = value.Width;
            else value.Width = Width;
            return value;
        }
    }
}
